# @Time : 2023/1/5
# @Author : SDAJAVA

import urllib.request
import urllib.parse

# get请求
base_url = 'https://www.baidu.com/s?'

# 汉字转unicode
name = urllib.parse.quote("周杰伦")
print(name)

# urlencode的应用场景：多参数
data = {
    'wd': '周杰伦',
    'sex': '男',
    'location': '中国台湾省',
}

new_data = urllib.parse.urlencode(data)
print(new_data)

url = base_url + new_data

print(url)
# UA 请求对象的定制 为了解决反爬的一种手段
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
}

# # 请求对象定制
# request = urllib.request.Request(url=url, headers=headers)
# # 模拟浏览器向服务器发送请求
# response = urllib.request.urlopen(request)
# # 获取响应内容
# content = response.read().decode('utf-8')
# # 打印内容
# print(content)

# post请求

url = 'https://fanyi.baidu.com/sug'

data_1 = {
    'kw': 'spider',
}
# post请求参数必须要进行编码
data_1 = urllib.parse.urlencode(data_1).encode('utf-8')
# post的请求参数是不会拼接到url的后面，需要放在请求对象定制的参数中
# post请求的参数必须进行编码
request = urllib.request.Request(url=url, data = data_1,headers=headers)
# 发送请求
response = urllib.request.urlopen(request)

content = response.read().decode('utf-8')
print(content)